package test11;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ling
 * Date: 2022-08-07
 * Time: 10:06
 */
class MyTask implements Comparable<MyTask>{
    private Runnable command;
    private long time;
    public MyTask(Runnable command,long after){
        this.command=command;
        this.time=System.currentTimeMillis()+after;
    }
    public void run(){
        command.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time-o.time);
    }
}
public class MyTimer {
    private Object locker=new Object();
    private PriorityBlockingQueue<MyTask> queue=new PriorityBlockingQueue<>();
    public void schedule(Runnable command,long after){
        MyTask myTask=new MyTask(command,after);
        synchronized (locker) {
            queue.put(myTask);
            locker.notify();
        }
    }
    public MyTimer(){
        Thread t=new Thread(()->{
            while(true){
                try {
                    synchronized (locker) {
                        MyTask myTask = queue.take();
                        long curTime = System.currentTimeMillis();
                        if (myTask.getTime() > curTime) {
                            queue.put(myTask);
                            locker.wait(myTask.getTime()-curTime);
                        } else {
                            myTask.run();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
